import { fetchHome } from '../../services/home/home';
import { fetchGoodsList } from '../../services/good/fetchGoods';
import Toast from 'tdesign-miniprogram/toast/index';
import { getAllStudent } from '../../services/students/studentData';
import { getSelectedSchoolId, getSelectedStudentId, getSelectedSchoolData, getStudentsList, getRight, getSizeList, getShoesSizeList } from '../../userData/userData';
Page({
  data: {
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    studentInfo: {
      name: '测试',
      school: '一中',
      grade: '三年纪',
      class: '二班',
      sex: '男',
      height: '180cm',
      weight: '67kg',
      specialBody: '否'
    },
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    visible: false,
    //当前选购商品的最大数量
    currentGoodMaxNum: 0,
    currentSize: 0,
    sizeList: [
      // { id: 1, info: '120(身高110-120cm 体重20-24kg)' },
      // { id: 2, info: '130(身高120-130cm 体重25-29kg)' },
      // { id: 3, info: '140(身高130-140cm 体重30-34kg)' },
      // { id: 4, info: '150(身高140-150cm 体重35-40kg)' },
      // { id: 5, info: '160(身高150-160cm 体重45-50kg)' },
      // { id: 6, info: '165(身高160-164cm 体重50-54kg)' },
      // { id: 7, info: '170(身高165-170cm 体重55-64kg)' },
      // { id: 8, info: '175(身高170-175cm 体重60-69kg)' },
      // { id: 9, info: '180(身高175-180cm 体重70-75kg)' },
      // { id: 10, info: '190(身高180-190cm 体重75-85kg)' }
    ],
    //当前选购的商品
    currentGood: {
      name: '',
      price: '',
      img: ''
    },
    //商品数量
    number: 1,
    isVisiter: false
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {
    this.getTabBar().init();
    if (this.data.studentInfo.i_id != getSelectedSchoolId()) {
      this.initStudent();
      this.loadHomePage();
    }
    else {
      this.initStudent();
    }
  },

  onLoad() {
    this.init();
  },

  onReachBottom() {
    return
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },
  initStudent() {
    const students = getStudentsList()

    students.forEach(element => {
      if (element._id == getSelectedStudentId()) {
        this.setData({ studentInfo: element })
      }
    });
  },
  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    this.setData({
      isVisiter: getRight() == "school"
    })
    fetchHome().then(({ swiper, tabList }) => {
      this.setData({
        tabList,
        imgSrcs: swiper,
        pageLoading: false,
      });
      this.loadGoodsList(true);
    });
    // this.initStudent()
  },

  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    this.loadGoodsList(true);
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }

    this.setData({ goodsListLoadStatus: 1 });

    const pageSize = this.goodListPagination.num;
    let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 0;
    }

    try {
      const nextList = await fetchGoodsList(pageIndex, pageSize);
      this.setData({
        goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
        goodsListLoadStatus: 0,
      });

      this.goodListPagination.index = pageIndex;
      this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({ goodsListLoadStatus: 3 });
    }
  },
  //查看详情
  goodListClickHandle(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
    return
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
    });
  },
  baseInfoClickHandle(e) {
    wx.navigateTo({
      url: `/pages/usercenter/students/list/index?selectMode=1&id=${e.id}`,
    });
  },
  stepperhandleChange(e) {
    const { value } = e.detail;
    this.setData({
      number: value
    });
  },
  //点击选购
  goodListAddCartHandle(e) {
    this.setData({ sizeList: [] })
    this.setData({
      currentGood: e.detail.goods,
      currentGoodMaxNum: e.detail.goods.number
    })
    const id = this.data.currentGood._id
    wx.cloud.callFunction({
      name: "good_getParameterforGood",
      data: {
        good_id: id
      }
    }).then(res => {
      let { value } = res.result[0];
      if (this.data.currentGood.tabType == 9999) {
        this.setData({ sizeList: getShoesSizeList("3|4|5|6|7|8|9|10|11|12|13|14") })
      }
      else {
        this.setData({ sizeList: getSizeList(value) })
      }


      // this.setData({ sizeList: value.split(',') })

    })
    this.onVisibleChange()
  },
  //添加到购物车
  addToShoppCart() {
    if (this.data.number <= 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择商品数量',
      });
      return;
    }
    if (!this.data.sizeList[this.data.currentSize]) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择商品尺码',
      });
      return;
    }
    wx.cloud.callFunction({
      name: "shop_addCart",
      data: {
        student_id: getSelectedStudentId(),//"e54110dd644a2b390023ffb23b446299",
        good_id: this.data.currentGood._id,//"53029201644b87ee000d021b3b9dcd17",
        number: this.data.number,
        parameter: this.data.sizeList[this.data.currentSize]
      }
    }).then(res => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '成功加入购物车',
      });
      this.setData({
        visible: false
      });
    })
    wx.switchTab({
      url: 'url',
    })
  },
  //立刻购买
  buyAtonce() {
    if (this.data.number <= 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择商品数量',
      });
      return;
    }
    if (!this.data.sizeList[this.data.currentSize]) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择商品尺码',
      });
      return;
    }
    // wx.cloud.callFunction({
    //   name: "shop_addCart",
    //   data: {
    //     student_id: getSelectedStudentId(),//"e54110dd644a2b390023ffb23b446299",
    //     good_id: this.data.currentGood.g_id,//"53029201644b87ee000d021b3b9dcd17",
    //     number: this.data.number,
    //     parameter: this.data.sizeList[this.data.currentSize]
    //   }
    // }).then(res => {
    //   wx.switchTab({ url: '/pages/cart/index' });
    // })
    var chooseGoodsData = [{
      s_id: getSelectedStudentId(),//"e54110dd644a2b390023ffb23b446299",
      g_id: this.data.currentGood._id,//"53029201644b87ee000d021b3b9dcd17",
      number: this.data.number,
      parameter: this.data.sizeList[this.data.currentSize],
      price: this.data.currentGood.price,
      thumb: this.data.currentGood.img,
      title: this.data.currentGood.title,
      description: this.data.currentGood.name,
    }];
    wx.cloud.callFunction({
      name: 'pay',
      data: {
        body: '支付',
        detail: JSON.stringify(chooseGoodsData),
        attach: '',
        totalFee: this.data.currentGood.price * this.data.number * 100
      },
      success: res => {
        if (res.result.errCode == 0) {
          const payment = res.result.payment
          wx.requestPayment({
            ...payment,
            success(res) {
            },
            fail(err) {
              console.warn('pay fail', err)
            }
          })
        } else if (res.result.errCode == -1) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.result.errMsg,
          });
        }
      },
      fail: console.error,
    })
  },
  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },

  navToActivityDetail({ detail }) {
    const { index: promotionID = 0 } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },
  //popup框显隐
  onVisibleChange() {
    this.setData({
      visible: !this.data.visible
    });
    if (this.data.visible) {
      this.setData({
        number: 1,
        currentSize: 0
      })
    }
  },
  //选择尺码
  onChangeSize(e) {
    const { num } = e.target.dataset
    this.setData({
      currentSize: num
    })
  }
});
